package com.hp.ssmp.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hp.ssmp.util.R;
import com.hp.ssmp.util.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    //请求前
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        //从请求头中获取token
        String token = request.getHeader("token");
        //使用token到redis中进行有效验证
        if(null != token && redisTemplate.getExpire(token) > 0){
            //token不为空并且失效时间大于0 - 登录状态有效
            //重置token的失效时间
            redisTemplate.expire(token,1800, TimeUnit.SECONDS);
            return true;
        }else{
            //响应给客户端token已失效
            R r = R.error(StatusCode.TOKEN_EXPIRED,"token已失效,请重新登录");
            //将R对象转换为json字符串
            ObjectMapper objectMapper = new ObjectMapper();
            response.getWriter().println(objectMapper.writeValueAsString(r));
            return false;
        }
    }

    //请求后
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
